<template>
  <div class="login-container">
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        label-position="left"
    >
      <h2 class="title">系统登录</h2>

      <el-form-item prop="username">
        <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="el-icon-user"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
            @keyup.enter.native="handleLogin"
        />
      </el-form-item>

      <el-button
          type="primary"
          style="width: 100%; margin-bottom: 30px"
          :loading="loading"
          @click="handleLogin"
      >
        登录
      </el-button>
    </el-form>
  </div>
</template>

<script>
import { login, getCurrentUser } from '@/api/login'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '密码不能少于6位', trigger: 'blur'}
        ]
      },
      loading: false
    }
  },
  methods: {
    async handleLogin() {
      // 触发表单验证
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) {
          console.warn('表单验证失败')
          return
        }

        this.loading = true
        try {
          // 1. 调用登录接口
          const res = await login(this.loginForm)
          const token = res.data;

          // 2. 保存 token 到 Vuex（假设你的 store 支持）
          await this.$store.dispatch('login', token)
          console.log('✅ 登录后 token:', this.$store.getters.token)
          // 3. 获取用户信息
          const userRes = await getCurrentUser()
          await this.$store.dispatch('setUser', userRes.data)

          // 4. 跳转
          this.$message.success('登录成功！')
          this.$router.push(this.$route.query.redirect || '/')

        } catch (error) {
          // 这里会捕获 axios 请求错误（如 403、400、网络错误等）
          console.error('登录请求失败:', error)
          let msg = '登录失败，请检查用户名或密码'
          if (error.response) {
            const status = error.response.status
            if (status === 403) {
              msg = '禁止访问：权限不足或请求被拒绝'
            } else if (status === 400) {
              msg = '请求参数错误'
            } else if (status === 500) {
              msg = '服务器内部错误'
            }
          }
          this.$message.error(msg)
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  width: 350px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style>